package org.system.core.controller.monitor;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.system.core.annotation.Log;
import org.system.core.common.Constants;
import org.system.core.common.Result;
import org.system.core.config.RedisCache;
import org.system.core.domain.entity.SysUserOnline;
import org.system.core.domain.model.LoginUser;
import org.system.core.enums.BusinessType;
import org.system.core.service.monitor.SysUserOnlineService;
import org.system.core.utils.StringUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

/**
 * @author baoRoot
 */
@RestController
@Api(tags = {"在线用户监控模块"})
@RequestMapping("/monitor/online")
public class SysUserOnlineController {

    private static final Logger logger = LoggerFactory.getLogger(SysUserOnlineController.class);

    @Autowired
    private SysUserOnlineService sysUserOnlineService;

    @Autowired
    private RedisCache redisCache;

    @GetMapping("/list")
    @ApiOperation("获取在线用户列表")
    @PreAuthorize("@ss.hasPermi('monitor:online:list')")
    public Result<List<SysUserOnline>> list(String ipaddr, String userName) {
        logger.info("获取在线用户列表: {}, {}", ipaddr, userName);
        Collection<String> keys = redisCache.keys(Constants.LOGIN_TOKEN_KEY + "*");
        List<SysUserOnline> userOnlineList = new ArrayList<>();
        if (keys != null) {
            for (String key : keys) {
                LoginUser user = redisCache.getCacheObject(key);
                if(StringUtils.isNotEmpty(ipaddr) && StringUtils.isNotEmpty(userName)){
                    userOnlineList.add(sysUserOnlineService.selectOnlineByInfo(ipaddr, userName, user));
                } else if(StringUtils.isNotEmpty(ipaddr)) {
                    userOnlineList.add(sysUserOnlineService.selectOnlineByIpaddr(ipaddr, user));
                }else if(StringUtils.isNotEmpty(userName) && StringUtils.isNotNull(user.getUser())) {
                    userOnlineList.add(sysUserOnlineService.selectOnlineByUserName(userName, user));
                } else {
                    userOnlineList.add(sysUserOnlineService.loginUserToUserOnline(user));
                }
            }
            Collections.reverse(userOnlineList);
            userOnlineList.removeAll(Collections.singleton(null));
        }
        return Result.ok(userOnlineList);
    }

    @DeleteMapping("/{tokenId}")
    @ApiOperation("强退用户")
    @Log(title = "在线用户", businessType = BusinessType.FORCE)
    @PreAuthorize("@ss.hasPermi('monitor:online:forceLogout')")
    public Result<String> forceLogout(@PathVariable String tokenId){
        logger.info("强退用户: {}", tokenId);
        redisCache.deleteObject(Constants.LOGIN_TOKEN_KEY + tokenId);
        return Result.ok();
    }

}
